package com.itheima.controller;

import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookServlet {
    @Autowired
    private BookService bookService;

    @GetMapping
    public Result selectAll(){
        List<Book> books = bookService.selectAll();
        Integer code=books!=null? Code.GET_OK:Code.GET_ERR;
        String msc=books!=null?"":"数据查询失败，请重试！";
        return new Result(code,msc,books);
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable int id){
        if (id<0){
            throw new BusinessException(Code.BUSIN_ERR,"你的输入有误");
        }
        Book book = bookService.selectById(id);
        Integer code=book!=null? Code.GET_OK:Code.GET_ERR;
        String msc=book!=null?"":"数据查询失败，请重试！";
        return new Result(code,msc,book);
    }

    @PostMapping
    public Result add(@RequestBody Book book){
        boolean flag = bookService.add(book);
        return new Result(flag?Code.ADD_OK:Code.ADD_ERR,null,flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable int id){
        boolean flag = bookService.deleteById(id);
        return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,null,flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book){
        boolean flag = bookService.update(book);
        return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR,null,flag);

    }

}
